<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--新闻资讯数据-->
        <pane size="84">
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
              <el-form-item label="新闻标题" prop="title">
                <el-input v-model="queryParams.title" placeholder="请输入新闻标题" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="发布状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="发布状态" clearable style="width: 240px">
                  <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:article:add']">新增</el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="50" align="center"  :show-overflow-tooltip="true"/>
              <el-table-column label="编号" align="center" key="articleId" prop="articleId" v-if="columns.articleId.visible" :show-overflow-tooltip="true"/>
              <el-table-column label="新闻标题" align="center" key="title" prop="title" v-if="columns.title.visible" :show-overflow-tooltip="true" />
              <el-table-column label="作者" align="center" key="author" prop="author" v-if="columns.author.visible" :show-overflow-tooltip="true" />
              <el-table-column label="排序" align="center" key="sort" prop="sort" v-if="columns.sort.visible" :show-overflow-tooltip="true" />
              <el-table-column label="状态" align="center" key="status" v-if="columns.status.visible" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
                </template>
              </el-table-column>
              <el-table-column label="发布时间" align="center" prop="createTime" v-if="columns.publishDate.visible" width="160">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.publishDate) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="preview(scope.row)">预览</el-button>
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:user:edit']">修改</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="新闻标题" prop="title">
              <el-input v-model="form.title" placeholder="新闻标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input v-model="form.author" placeholder="作者" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来源" prop="source">
              <el-input v-model="form.source" placeholder="来源" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="发布时间" prop="title">
              <el-date-picker type="datetime" v-model="form.publishDate" format="yyyy-MM-dd HH:mm:ss"
                              value-format="yyyy-MM-dd HH:mm:ss" :style="{width: '100%'}" placeholder="请选择发布时间" clearable>
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="新闻摘要">
              <el-input v-model="form.intro" type="textarea" placeholder="请输入新闻摘要"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="新闻图片">
              <el-upload
                multiple
                :action="uploadImgUrl"
                list-type="picture-card"
                :on-success="handleUploadCateImageSuccess"
                :before-upload="handleCateImageBeforeUpload"
                :limit="limit"
                :on-error="handleCateImageUploadError"
                :on-exceed="handleCateImageExceed"
                ref="imageUpload"
                :on-remove="handleCateImageUploadDelete"
                :show-file-list="true"
                :headers="headers"
                :file-list="imageList"
                :on-preview="handleCateImagePictureCardPreview"
                :class="{hide: this.imageList.length >= this.limit}"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <!-- 上传提示 -->
              <div class="el-upload__tip" slot="tip" v-if="showTip">
                请上传
                <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
                <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
                的文件
              </div>
              <el-dialog
                :visible.sync="dialogVisible"
                title="预览"
                width="800"
                append-to-body
              >
                <img
                  :src="dialogImageUrl"
                  style="display: block; max-width: 100%; margin: 0 auto"
                />
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上线状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否置顶">
              <el-radio-group v-model="form.isTop">
                <el-radio v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="新闻内容">
              <editor v-model="form.content" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件上传">
              <el-upload
                multiple
                :action="uploadImgUrl"
                :before-upload="handleAttachmentBeforeUpload"
                :file-list="attachmentList"
                :limit="limit"
                :on-error="handleAttachmentUploadError"
                :on-exceed="handleAttachmentExceed"
                :on-success="handleAttachmentUploadSuccess"
                :show-file-list="false"
                :headers="headers"
                class="upload-file-uploader"
                ref="fileUpload"
              >
                <!-- 上传按钮 -->
                <el-button size="mini" type="primary">选取文件</el-button>
                <!-- 上传提示 -->
                <div class="el-upload__tip" slot="tip" v-if="showTip">
                  请上传
                  <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
                  <template v-if="attachmentfileType"> 格式为 <b style="color: #f56c6c">{{ attachmentfileType.join("/") }}</b> </template>
                  的文件
                </div>
              </el-upload>

              <!-- 文件列表 -->
              <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
                <li :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in attachmentList">
                  <el-link :underline="false" :href="`${file.url}`" target="_blank">
                    <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
                  </el-link>
                  <div class="ele-upload-list__item-content-action">
                    <el-link :underline="false" @click="handleAttachmentDeleteFile(index)" type="danger">删除</el-link>
                  </div>
                </li>
              </transition-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>



<script>
import {listArticle, getArticle, addArticle, updateArticle, delArticle, changeArticleStatus} from "@/api/system/article"
import {getSite, getToken} from "@/utils/auth"
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import {listToString, splitImages} from "@/api/tool/upload";

export default {
  name: "Article",
  dicts: ['sys_normal_disable', 'sys_yes_no'],
  components: { Splitpanes, Pane },
  props: {
    // 图片数量限制
    limit: {
      type: Number,
      default: 1,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 50,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    attachmentfileType: {
      type: Array,
      default: () => ["doc", "docx", "pdf", "xls", "xlsx"],
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 新闻资讯表格数据
      articleList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        tenantId: getSite(),
        articleType: 1,
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        status: undefined
      },
      // 查询参数
      editQueryParams: {
        tenantId: getSite()
      },
      // 列信息
      columns: {
        articleId: { label: '编号', visible: true },
        title: { label: '新闻标题', visible: true },
        author: { label: '作者', visible: true },
        sort: { label: '排序', visible: true },
        status: { label: '状态', visible: true },
        publishDate: { label: '发布时间', visible: true }
      },
      // 表单校验
      rules: {
        title: [{ required: true, message: "新闻标题不能为空", trigger: "blur" }],
        intro: [{ required: true, message: "新闻摘要不能为空", trigger: "blur" }],
        publishDate: [{required: true, message: '请选择发布时间', trigger: 'change'}],
        sort: [{ required: true, message: "排序不能为空", trigger: "blur" }]
      },
      previewUrl: process.env.VUE_APP_ARTICLE_URL,
      // 上传的图片服务器地址
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      // 上传图片个数
      number: 0,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],   //新闻资讯图
      imageList: [],  //列表缩略图
      attachmentList: [], //附件上传
      uploadList: [], //临时上传列表
      dialogVisible: false,
      dialogImageUrl: "",
    }
  },
  watch: {
    // 根据名称筛选部门树
    cateName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    /** 查询新闻资讯列表 */
    getList() {
      this.loading = true
      listArticle(this.queryParams).then(response => {
          this.articleList = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    },
    // 过滤禁用的分类
    filterDisabledCate(cateList) {
      return cateList.filter(cate => {
        if (cate.disabled) {
          return false
        }
        if (cate.children && cate.children.length) {
          cate.children = this.filterDisabledCate(cate.children)
        }
        return true
      })
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用"
      this.$modal.confirm('确认要' + text + '"' + row.title + '"的新闻资讯吗？').then(function() {
        return changeArticleStatus(row.articleId, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + "成功")
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0"
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        articleId: undefined,
        cateId: undefined,
        title: undefined,
        status: "0",
        content: undefined,
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.queryParams.deptId = undefined
      this.$refs.tree.setCurrentKey(null)
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加新闻资讯"
      //新闻资讯图
      this.fileList = [];
      //列表缩略图
      this.imageList = [];
      //标签词条
      this.labels = [];
      //性能参数
      this.params = [];
      //附件
      this.attachmentList = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const articleId = row.articleId
      getArticle(articleId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改新闻资讯"
        //新闻图片
        this.imageList = [];
        if(this.form.images){
          const imageArr = this.form.images.split(';');
          for (var i = 0; i < imageArr.length; i++) {
            this.imageList.push({ name: imageArr[i], fileName: imageArr[i],url: process.env.VUE_APP_BASE_API + imageArr[i] });
          }
        }
        //附件
        this.attachmentList = [];
        if(this.form.attachment){
          const imageArr = this.form.attachment.split(';');
          for (var i = 0; i < imageArr.length; i++) {
            this.attachmentList.push({ name: imageArr[i], fileName: imageArr[i],url: process.env.VUE_APP_BASE_API + imageArr[i] });
          }
        }
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 租户ID
          this.form.tenantId = getSite();
          this.form.articleType = this.queryParams.articleType;
          // 列表缩略图
          this.form.images = splitImages(this.imageList);
          //附件
          this.form.attachment = splitImages(this.attachmentList);
          const content = this.form.content;
          this.form.content = btoa(unescape(encodeURIComponent(content)));
          if(!this.form.isTop){
            this.form.isTop = 'N';
          }
          if (this.form.articleId != undefined) {
            updateArticle(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addArticle(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const articleId = row.articleId
      this.$modal.confirm('是否确认删除名称为"' + row.title + '"的数据项？').then(function() {
        return delArticle(articleId)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /**新闻预览 **/
    preview(row){
      const articleId = row.articleId;
      const url = this.previewUrl.replace('#{articleId}',articleId);
      window.open(url);

    },
    //分类图片方法
    // 上传前loading加载
    handleCateImageBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 上传成功回调
    handleUploadCateImageSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.newFileName, fileName: res.fileName,url: res.url });
        this.uploadedCateImageSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedCateImageSuccessfully();
      }
    },
    // 上传结束处理
    uploadedCateImageSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.imageList = this.imageList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", listToString(this.baseUrl,this.imageList));
        this.$modal.closeLoading();
      }
    },
    // 文件个数超出
    handleCateImageExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleCateImageUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 删除图片
    handleCateImageUploadDelete(file) {
      const findex = this.imageList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.imageList.splice(findex, 1);
        this.$emit("input", listToString(this.baseUrl,this.imageList));
      }
    },
    // 预览
    handleCateImagePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    //附件上传
    // 上传前loading加载
    handleAttachmentBeforeUpload(file) {
      let isImg = false;
      if (this.attachmentfileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.attachmentfileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.attachmentfileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 上传成功回调
    handleAttachmentUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.newFileName, fileName: res.fileName,url: res.url });
        this.uploadedAttachmentSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedAttachmentSuccessfully();
      }
    },
    // 上传结束处理
    uploadedAttachmentSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.attachmentList = this.attachmentList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", listToString(this.baseUrl,this.attachmentList));
        this.$modal.closeLoading();
      }
    },
    // 文件个数超出
    handleAttachmentExceed() {
      this.$modal.msgError(`附件上传数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleAttachmentUploadError() {
      this.$modal.msgError("上传附件失败，请重试");
      this.$modal.closeLoading();
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    // 删除文件
    handleAttachmentDeleteFile(index) {
      this.attachmentList.splice(index, 1);
      this.$emit("input", listToString(this.attachmentList));
    },
  }
}
</script>
